package com.zone.core.base.adapter

import android.annotation.SuppressLint
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.annotation.LayoutRes
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import androidx.paging.PagedListAdapter
import androidx.recyclerview.widget.DiffUtil
import com.zone.core.base.BindingViewHolder

/**last
 *Author: last
 *Time: 2023-11-6
 *Description: xxx
 */
abstract class BasePageAdapter<T, BINDING : ViewDataBinding> :
    PagedListAdapter<T, BindingViewHolder<T, BINDING>>(
        CustomDiffItemCallback<T>()
    ) {

    //列表项按下监听
    var itemClickListener: OnItemClickListener<T>? = null

    var itemEventHandler: Any? = null

    /**
     * 布局id
     * @return Int
     */
    @LayoutRes
    abstract fun getLayoutRes(): Int

    override fun onCreateViewHolder(
        parent: ViewGroup,
        viewType: Int
    ): BindingViewHolder<T, BINDING> {
        val binding = DataBindingUtil.inflate<BINDING>(
            LayoutInflater.from(parent.context),
            getLayoutRes(),
            parent,
            false
        )
        val holder = BindingViewHolder<T, BINDING>(binding)
        binding.lifecycleOwner = holder
        bindClick(holder, binding)
        return holder
    }

    override fun onBindViewHolder(holder: BindingViewHolder<T, BINDING>, position: Int) {
        holder.bind(getItem(position))
        holder.setItemEventHandler(itemEventHandler)
    }

    /**
     * 事件绑定
     * @param holder BindingViewHolder<*, *>
     * @param binding BINDING
     */
    private fun bindClick(holder: BindingViewHolder<*, *>, binding: BINDING) {
        binding.root.setOnClickListener { _ ->
            val position = holder.layoutPosition
            itemClickListener?.onItemClick(getItem(position), position)
        }
    }

    override fun onViewAttachedToWindow(holder: BindingViewHolder<T, BINDING>) {
        super.onViewAttachedToWindow(holder)
        holder.markAttach()
    }

    override fun onViewDetachedFromWindow(holder: BindingViewHolder<T, BINDING>) {
        super.onViewDetachedFromWindow(holder)
        holder.markDetach()
    }

    interface OnItemClickListener<T> {
        fun onItemClick(t: T?, position: Int)
    }

    /**
     * 比较器
     * @param T
     */
    class CustomDiffItemCallback<T> : DiffUtil.ItemCallback<T>() {
        override fun areItemsTheSame(oldItem: T & Any, newItem: T & Any): Boolean =
            oldItem === newItem

        @SuppressLint("DiffUtilEquals")
        override fun areContentsTheSame(oldItem: T & Any, newItem: T & Any): Boolean =
            oldItem === newItem


    }
}